package factory_pattern.simple_factory.connection_impl;

import java.net.Socket;

public class TcpConnection implements NetworkConnection {
    private final String host;
    private final int port;
    private Socket socket;

    // 构造器：传入TCP连接参数
    public TcpConnection(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public boolean connect() {
        try {
            socket = new Socket(host, port);
            System.out.printf("[TCP] 连接成功：%s:%d%n", host, port);
            return true;
        } catch (Exception e) {
            System.out.printf("[TCP] 连接失败：%s%n", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendData(byte[] data) {
        if (socket == null || !socket.isConnected()) {
            System.out.println("[TCP] 连接未建立，无法发送");
            return false;
        }
        try {
            socket.getOutputStream().write(data);
            System.out.printf("[TCP] 发送成功：%d 字节%n", data.length);
            return true;
        } catch (Exception e) {
            System.out.printf("[TCP] 发送失败：%s%n", e.getMessage());
            return false;
        }
    }

    @Override
    public void close() {
        if (socket != null) {
            try {
                socket.close();
                System.out.printf("[TCP] 连接关闭：%s:%d%n", host, port);
            } catch (Exception e) {
                System.out.printf("[TCP] 关闭失败：%s%n", e.getMessage());
            } finally {
                socket = null;
            }
        }
    }
}